<template>
  <div class="add-user-modal" v-if="isVisible" @click="closeModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>新增用户</h3>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <form @submit.prevent="handleSubmit" class="user-form">
        <div class="form-group">
          <label for="name">用户名 <span class="required">*</span></label>
          <input
            id="name"
            type="text"
            v-model="form.name"
            placeholder="请输入用户名"
            required
            :class="{ error: errors.name }"
          >
          <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
        </div>
        
        <div class="form-group">
          <label for="email">邮箱 <span class="required">*</span></label>
          <input
            id="email"
            type="email"
            v-model="form.email"
            placeholder="请输入邮箱地址"
            required
            :class="{ error: errors.email }"
          >
          <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
        </div>
        
        <div class="form-group">
          <label for="role">角色 <span class="required">*</span></label>
          <select id="role" v-model="form.role" required :class="{ error: errors.role }">
            <option value="">请选择角色</option>
            <option value="admin">管理员</option>
            <option value="moderator">审核员</option>
            <option value="user">普通用户</option>
          </select>
          <span v-if="errors.role" class="error-message">{{ errors.role }}</span>
        </div>
        
        <div class="form-group">
          <label for="status">状态</label>
          <select id="status" v-model="form.status">
            <option value="active">活跃</option>
            <option value="inactive">禁用</option>
          </select>
        </div>
        
        <div class="form-actions">
          <button type="button" class="btn-cancel" @click="closeModal">取消</button>
          <button type="submit" class="btn-submit" :disabled="isSubmitting">
            {{ isSubmitting ? '添加中...' : '添加用户' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useUserStore } from '../stores/user'

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'success'])

const userStore = useUserStore()
const isSubmitting = ref(false)

// 表单数据
const form = reactive({
  name: '',
  email: '',
  role: '',
  status: 'active'
})

// 表单验证错误
const errors = reactive({
  name: '',
  email: '',
  role: ''
})

// 重置表单
const resetForm = () => {
  form.name = ''
  form.email = ''
  form.role = ''
  form.status = 'active'
  
  // 清除错误
  errors.name = ''
  errors.email = ''
  errors.role = ''
}

// 验证表单
const validateForm = () => {
  let isValid = true
  
  // 清除之前的错误
  errors.name = ''
  errors.email = ''
  errors.role = ''
  
  // 验证用户名
  if (!form.name.trim()) {
    errors.name = '用户名不能为空'
    isValid = false
  } else if (form.name.length < 2) {
    errors.name = '用户名至少需要2个字符'
    isValid = false
  }
  
  // 验证邮箱
  if (!form.email.trim()) {
    errors.email = '邮箱不能为空'
    isValid = false
  } else {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(form.email)) {
      errors.email = '邮箱格式不正确'
      isValid = false
    } else {
      // 检查邮箱是否已存在
      const existingUser = userStore.users.find(user => user.email === form.email)
      if (existingUser) {
        errors.email = '邮箱已存在'
        isValid = false
      }
    }
  }
  
  // 验证角色
  if (!form.role) {
    errors.role = '请选择用户角色'
    isValid = false
  }
  
  return isValid
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }
  
  isSubmitting.value = true
  
  try {
    // 调用store的addUser方法
    const newUser = userStore.addUser({
      name: form.name.trim(),
      email: form.email.trim(),
      role: form.role,
      status: form.status
    })
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 成功提示
    emit('success', newUser)
    
    // 重置表单并关闭模态框
    resetForm()
    closeModal()
    
  } catch (error) {
    console.error('添加用户失败:', error)
    alert('添加用户失败，请稍后重试')
  } finally {
    isSubmitting.value = false
  }
}

// 关闭模态框
const closeModal = () => {
  resetForm()
  emit('close')
}

// 计算属性：检查是否有权限添加用户
const canAddUser = computed(() => {
  return userStore.hasPermission('write')
})
</script>

<style scoped>
.add-user-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 0;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  animation: slideIn 0.3s ease;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #95a5a6;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #e74c3c;
}

.user-form {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #2c3e50;
}

.required {
  color: #e74c3c;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #3498db;
}

.form-group input.error,
.form-group select.error {
  border-color: #e74c3c;
}

.error-message {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 30px;
}

.btn-cancel {
  padding: 10px 20px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-cancel:hover {
  background: #f5f5f5;
}

.btn-submit {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-submit:hover:not(:disabled) {
  background: #2980b9;
}

.btn-submit:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style> 